package com.yangluyao.test.CAS;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author YLY
 * @ClassName CASDemo
 * @Date 2020/4/30
 * @Version 1.0.2
 */
public class CASDemo {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(5);
        System.out.println(atomicInteger.compareAndSet(5, 2019)+"\t current data "+atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(5, 2020)+"\t current data "+atomicInteger.get());
    }
}

class User{
    private String username;
    private int age;

    public User(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }

    public static void main(String[] args) {
        User zhangsan = new User("张三", 15);
        User lisi = new User("李四", 20);
        AtomicReference<User> userAtomicReference = new AtomicReference<>();
        userAtomicReference.set(zhangsan);
        System.out.println(userAtomicReference.compareAndSet(zhangsan, lisi)+"\t"+userAtomicReference.get().toString());
        System.out.println(userAtomicReference.compareAndSet(lisi, zhangsan)+"\t"+userAtomicReference.get().toString());
        System.out.println(userAtomicReference.compareAndSet(zhangsan, lisi)+"\t"+userAtomicReference.get().toString());
    }
}
